
package com.netease.xone.fragment;

import preferMgr.XonePrefHelper;
import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.LoopBack;
import protocol.meta.User;
import Utils.XoneUtil;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.netease.cache.CacheManager;
import com.netease.image.ImageManager;
import com.netease.log.NTLog;
import com.netease.pkgRelated.XoneConsts;
import com.netease.pkgRelated.XoneConsts.ACCOUNT_TYPE;
import com.netease.pkgRelated.XoneConsts.SETTING_CONTAINER_TYPE;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityAccountMgr;
import com.netease.xone.activity.ActivityLogin;
import com.netease.xone.activity.ActivitySettingContainer;
import com.netease.xone.activity.ActivityWBList;
import com.netease.xone.view.ProfileView;
import com.netease.xone.view.SettingItemView;

import db.manager.ManagerAccount;
import db.manager.ManagerAccount.Account;

public class FragSettingMain extends FragmentBase implements OnClickListener,IFragmentMain {

    private static final String TAG = "FragSettingMain";
    private boolean mBIsLogin = false;
    private SettingItemView  mPicQualityItem,mAboutItem/*,mCacheItem*/;
    private CheckBox mReadMode;
    private TextView mTxAcc,mTxAccType,mTxCacheProgress;
    private ProfileView mAvatar;
//    private RelativeLayout mAvatarLay;
    private ProgressBar mCachePregressBar;
    private int mProgress;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        NTLog.v(TAG, "onCreateView");
        setHasOptionsMenu(true);
        View view = inflater.inflate(R.layout.fragment_setting_main, container, false);
        findViews(view);
//        getActivity().setTitle(R.string.main_tab_option);
        return view;
    }
    
//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        if (isVisibleToUser) {
//           getActivity().setTitle(R.string.main_tab_option);
//        }
//    }

    private void findViews(View view) {
        TextView tv = (TextView)view.findViewById(R.id.frag_setting_category_acc);
        tv.setText(R.string.setting_category_account);
        tv = (TextView)view.findViewById(R.id.frag_setting_category_read);
        tv.setText(R.string.setting_category_read);
        tv = (TextView)view.findViewById(R.id.frag_setting_category_notify);
        tv.setText(R.string.setting_category_notify);
        tv = (TextView)view.findViewById(R.id.frag_setting_category_other);
        tv.setText(R.string.setting_category_other);
        
        LinearLayout accItem = (LinearLayout)view.findViewById(R.id.frag_setting_item_acc);
        accItem.setOnClickListener(this);
        mTxAcc = (TextView)accItem.findViewById(R.id.setting_acc_title);
        mTxAccType = (TextView)accItem.findViewById(R.id.setting_description);
        mAvatar = (ProfileView)accItem.findViewById(R.id.profile_avatar);
//        mAvatarLay = (RelativeLayout)accItem.findViewById(R.id.profile_avatar_container);
        switchAcc();

        mPicQualityItem = (SettingItemView)view.findViewById(R.id.frag_setting_item_picquality);
        mPicQualityItem.setTitleText(getResources().getString(R.string.setting_item_picquality));
        mPicQualityItem.setOnClickListener(this);
        setPicQualityText();
        
        SettingItemView item  = null;
        
        item = (SettingItemView)view.findViewById(R.id.frag_setting_item_msg);
        item.setTitleText(getResources().getString(R.string.setting_item_msg));
        item.setOnClickListener(this);

        item = (SettingItemView)view.findViewById(R.id.frag_setting_item_push);
        item.setTitleText(getResources().getString(R.string.setting_item_push));
        item.setOnClickListener(this);

        LinearLayout cacheItem  = (LinearLayout)view.findViewById(R.id.frag_setting_item_cache);
        cacheItem.setOnClickListener(this);
        mCachePregressBar = (ProgressBar)cacheItem.findViewById(R.id.setting_cache_progress);
        mTxCacheProgress = (TextView)cacheItem.findViewById(R.id.setting_cache_progress_text);
//        mTxCacheProgress.setText(getString(R.string.setting_cache_progress,46));


        item = (SettingItemView)view.findViewById(R.id.frag_setting_item_share);
        item.setTitleText(getResources().getString(R.string.setting_item_share));
        item.setOnClickListener(this);

        item = (SettingItemView)view.findViewById(R.id.frag_setting_item_feedback);
        item.setTitleText(getResources().getString(R.string.setting_item_feedback));
        item.setOnClickListener(this);

        mAboutItem = (SettingItemView)view.findViewById(R.id.frag_setting_item_about);
        mAboutItem.setTitleText(getResources().getString(R.string.setting_item_about));
        mAboutItem.setOnClickListener(this);
        switchVersion();

        item = (SettingItemView)view.findViewById(R.id.frag_setting_item_recommend);
        item.setTitleText(getResources().getString(R.string.setting_item_recommond));
        item.setOnClickListener(this);
        
        mReadMode = (CheckBox)view.findViewById(R.id.setting_readmode_check);
        mReadMode.setChecked(XonePrefHelper.getReadModeText(getActivity()));
        mReadMode.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                XonePrefHelper.putReadModeText(getActivity(), isChecked);
                if(isChecked){
                    ImageManager.DownloadType = ImageManager.NO_DOWNLOAD;
                }else {
                    ImageManager.DownloadType = ImageManager.ALL_DOWNLOAD;
                }
            }
        });
    }
    private void setProgressText(int progress) {
        if(progress >0 && progress < 100){
            mTxCacheProgress.setText(getString(R.string.setting_cache_progress,progress));
        } else {
            mTxCacheProgress.setVisibility(View.GONE);
            mCachePregressBar.setVisibility(View.GONE);
            showToast(R.string.setting_cache_done);
        }  
    }
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.frag_setting_item_acc:
                if (mBIsLogin) {
                    ActivityAccountMgr.launch(getActivity());
                } else {
                    ActivityLogin.launch(getActivity(),true);
                }
                break;
            case R.id.frag_setting_item_picquality:
                ActivitySettingContainer.launch(getActivity(),SETTING_CONTAINER_TYPE.set_pic_quality);
                break; 
            case R.id.frag_setting_item_msg:
                XoneService.getInstance().doGetAppSetting();
                ActivitySettingContainer.launch(getActivity(),SETTING_CONTAINER_TYPE.set_message);
                break;
            case R.id.frag_setting_item_push:
                XoneService.getInstance().doGetAppSetting();
                ActivitySettingContainer.launch(getActivity(),SETTING_CONTAINER_TYPE.set_push);
                break; 
            case R.id.frag_setting_item_share:
                ActivityWBList.launch(getActivity());
                break;
            case R.id.frag_setting_item_feedback:
                ActivitySettingContainer.launch(getActivity(),SETTING_CONTAINER_TYPE.set_feedback);
                break;
            case R.id.frag_setting_item_about:
                ActivitySettingContainer.launch(getActivity(),SETTING_CONTAINER_TYPE.set_about);
                break; 
            case R.id.frag_setting_item_recommend:
                ActivitySettingContainer.launch(getActivity(),SETTING_CONTAINER_TYPE.set_recommend);
                break;
            case R.id.frag_setting_item_cache:
                long cache = CacheManager.getCacheSize();
                CacheManager.deleteCache();
                if(cache < 5*XoneUtil.SIZE_UINT_MB){
                    mCachePregressBar.setVisibility(View.VISIBLE);
                    new Handler().postDelayed(mMyRunnable1, 500);
                } else {
                    mTxCacheProgress.setVisibility(View.VISIBLE);
                    mCachePregressBar.setVisibility(View.VISIBLE);
                    mProgress = 20;
                    setProgressText(mProgress);
                    new Handler().postDelayed(mMyRunnable, 100);
                }
                break;
        }
    }

    private Runnable mMyRunnable = new Runnable() {
        @Override
        public void run() {
            mProgress +=5;
            setProgressText(mProgress);
            if (mProgress < 100) {
                new Handler().postDelayed(mMyRunnable, 100);
            } 
        }
    };
    private Runnable mMyRunnable1 = new Runnable() {
        @Override
        public void run() {
            showToast(R.string.setting_cache_done);
            mCachePregressBar.setVisibility(View.GONE);
        }
    };
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        XoneService.getInstance().addListener(mXoneCallBack);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        XoneService.getInstance().removeListener(mXoneCallBack);
    }
    private void switchAcc(){
        if(mTxAcc == null) 
            return;
        Account acc = ManagerAccount.getInstance().getCurrentAccount();
        if (acc != null && acc.mUserType != ACCOUNT_TYPE.Anonymous) {
            mBIsLogin = true;
            mTxAcc.setText(acc.mNickName);
            mTxAccType.setText(XoneUtil.userTypeToString(getActivity(), acc.mUserType));
            mAvatar.setVisibility(View.VISIBLE);
//            if (!TextUtils.isEmpty(acc.mAvatar)) {
//                int size = getResources().getDimensionPixelSize(R.dimen.common_avatar_size);
//                int roundSize = getResources().getDimensionPixelSize(R.dimen.common_avatar_rounder);
//                mAvatar.setServerClipSize(size, size);
//                mAvatar.setLoadingImage(acc.mAvatar,ImageType.RoundMemCache,roundSize);
//            }
            mAvatar.setImageUrl(acc.mAttr,acc.mAvatar);
        } else {
            mBIsLogin = false;
            mTxAcc.setText(getResources().getString(R.string.setting_item_acc_login));
            mTxAccType.setText("");
            mAvatar.setVisibility(View.GONE);
        }
    }
    private void switchVersion(){
        if(mAboutItem == null)
            return;
        if(hasNewVersion(getActivity())){
            mAboutItem.setBtnText(getString(R.string.about_new_version));
        }else {
            mAboutItem.setBtnText("");
        }
        
    }
    private void setPicQualityText(){
        if(mPicQualityItem == null)
            return;
        int type = XonePrefHelper.getPicQuality(getActivity());
        int resId = 0;
        switch(type){
            case XoneConsts.PIC_QUALTY_TYPE.high:
            resId = R.string.picquality_set_high;
            break;
            case XoneConsts.PIC_QUALTY_TYPE.normal:
                resId = R.string.picquality_set_normal;
                break;
            case XoneConsts.PIC_QUALTY_TYPE.low:
                resId = R.string.picquality_set_low;
                break;
        }
        if(resId > 0){
            mPicQualityItem.setDesText(getString(resId));
        }
        
    }
    private XoneCallBack mXoneCallBack = new XoneCallBack() {

        @Override
        public void onLogin(int transactionId, User account) {
            switchAcc();
        }
        @Override
        public void onLoopBack(int transactionId, Object obj) {
            if(obj != null && obj instanceof LoopBack){
                LoopBack lb = (LoopBack)obj;
                if(lb.mType == XoneConsts.LOOPBACK_TYPE.pic_quality_set_changed){
                    setPicQualityText();
                }
            }
        };
        @Override
        public void onUpdateUser(int transactionId) {
            switchAcc();
        };
        
    };
    
    public static boolean hasNewVersion(Context context){
        boolean res = false;
        if(XonePrefHelper.getPreUpdateVersion(context).compareToIgnoreCase(XoneUtil.getNumberVersion(context)) >0 ){
            res = true;
        }
        return res;
        
    }

    @Override
    public void onPageSelected(int index) {
        getSherlockActivity().getSupportActionBar().setDisplayShowTitleEnabled(true);
        getActivity().setTitle(R.string.main_tab_option);
    }

    @Override
    public void onPageReSelected(int index) {
        // TODO Auto-generated method stub
        
    }
}
